package com.openstackapi.ctds.imp;




import java.security.KeyStore.Builder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient.OSClientV2;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.compute.Action;
import org.openstack4j.model.compute.Addresses;
import org.openstack4j.model.compute.RebootType;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.compute.ServerCreate;
import org.openstack4j.openstack.OSFactory;

import com.openstackapi.ctds.VMController;
import com.openstackapi.ctds.pojo.ActVMReq;
import com.openstackapi.ctds.pojo.BackupVMResp;
import com.openstackapi.ctds.pojo.CreateVMResp;
import com.openstackapi.ctds.pojo.DeleteVMResp;
import com.openstackapi.ctds.pojo.ModifyVMResp;
import com.openstackapi.ctds.pojo.QueryVMStatusResp;
import com.openstackapi.ctds.pojo.VMResourceInfo;

public class VMControllerImp implements VMController {

	@Override
	public CreateVMResp CreateVM(String ParamFlag, String ResourceTemplateID, VMResourceInfo vMResourceInfo,
			String AppID, String AppName, int Count, String Security) {

		
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		
		//处理XML参数
		
		 
		
		
		
		//创建虚拟机
		List<String> list_network=new ArrayList();
		list_network.add("127c1dd2-0218-4eaf-83b1-09b31c7ddade");
		ServerCreate sc = Builders.server().name("baater2").networks(list_network).flavor("2").image("3ee9e4d2-356d-4f6d-ac0e-6252d5c6930d").build();
	
		System.out.println(sc.getName());
		Server server = os.compute().servers().boot(sc);
//		server.getPowerState();
		
		
		return null;
	}

	@Override
	public ActVMReq ActVM(String VMID, int ActType) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
				
		Server server = os.compute().servers().get(VMID);
				
		/*
		 * 操作虚拟机
		 * 1：启动 start server
			2：暂停 
			3：恢复
			4：停止
			5：重启
		 */
		
		if(ActType == 1){
			//  start a Server    
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.START);
		}else if (ActType == 2){
			// Suspend a Server
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.SUSPEND);
			
		}else if (ActType == 3){
			// Resume a Server
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.RESUME);
			
		}else if (ActType == 4){
			// stop a Server
			ActionResponse ar = os.compute().servers().action(server.getId(), Action.STOP);
			
		}else if (ActType == 5){
			// reboot a Server
			ActionResponse ar = os.compute().servers().reboot(server.getId(), RebootType.SOFT);
			
		}
		
		
		
		
		return null;
	}

	
	 

	@Override
	public DeleteVMResp DeleteVM(String VMID) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		//delete specific server by ID	
		ActionResponse ar = os.compute().servers().delete(VMID);
		return null;
	}
	
	
	@Override
	public ModifyVMResp ModifyVM(String VMID, VMResourceInfo vMResourceInf) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
//		ActionResponse ar = os.compute().servers().update(VMID, ServerUpdateOptions.create().name("NewName"));
		os.compute().servers().updateMetadata(VMID, (Map<String, String>) vMResourceInf);
		return null;
	}
	
	
	@Override
	public QueryVMStatusResp QueryVMStatus(String VMID) {
		//登录认证
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
                .credentials("admin","ADMIN_PASS")
                .tenantName("admin")
                .authenticate();
		// list server by id
		Server server = os.compute().servers().get(VMID);
		
		
		// 
		if(server.getVmState() == "active"){
			int Status = 1;
			System.out.println("VM status " + Status);
		}else if(server.getVmState() == "building"){
			int Status = 0;
			System.out.println("VM status " + Status);
		}
		
		// operation ip
		String OperationIP = server.getAccessIPv4();
		/**
		 * NovaAddresses{
		 *   addresses = 
		 *     {基础网络 = 
		 *          [NovaAddress
		 *             {address=172.30.249.241, type=fixed, version=4, macaddr=fa:16:3e:ef:b3:b5, 
					}]}, 
			} 
		 */
		
		
		return null;
	}
	
	
	
	@Override
	public BackupVMResp BackupVM(String VMID) {
		
		
		//登录
		OSClientV2 os = OSFactory.builderV2()
                .endpoint("http://10.50.0.11:5000/v2.0")
            .credentials("admin","ADMIN_PASS")
            .tenantName("admin")
            .authenticate();
		
		// start backup server
		Server server = os.compute().servers().get(VMID);
		String imageId = os.compute().servers().createSnapshot(server.getId(), "Clean State Snapshot");
		
		BackupVMResp b = new BackupVMResp();
		
		b.setFaultstring(imageId);
		
		return null;
	}

	
	
	//test 
		public static void main(String[] args){
			
			
			OSClientV2 os = OSFactory.builderV2()
			                       .endpoint("http://10.50.0.10:5000/v2.0")
		                       .credentials("admin","ADMIN_PASS")
		                       .tenantName("admin")
		                       .authenticate();
			System.out.println("authentication complate");
	

			//list all server
			List<? extends Server> servers = os.compute().servers().list();
			for(Server s:servers){
				System.out.println(s);
			}
			/**
			 * NovaServer{id=5a57b5dd-4616-4a1a-a803-4c84469c6898, name=vfw-cloud, 
			 * image={id=6bbf2c8a-c303-4efb-ba62-a512df70b16b, 
			 * links=[{href=http://10.50.0.10:8774/c9c567c8f81b4af185bfa1def00dac9e/images/6bbf2c8a-c303-4efb-ba62-a512df70b16b, rel=bookmark}]},
			 * flavor=NovaFlavor{id=3fafc03a-b49e-4b04-8558-1b0cf8131a18, ephemeral=0, swap=0, rxtx_factor=1.0, links=[GenericLink{href=http://10.50.0.10:8774/c9c567c8f81b4af185bfa1def00dac9e/flavors/3fafc03a-b49e-4b04-8558-1b0cf8131a18, rel=bookmark}], }, 
			 * status=SHUTOFF, diskconfig=AUTO, userId=adc01ddd471243ecbb64ae0dc5734c3b, created=Wed Jul 27 14:45:57 CST 2016, updated=Tue Sep 20 09:32:30 CST 2016, 
			 * launched at=Wed Jul 27 14:46:12 CST 2016, tenantId=c9c567c8f81b4af185bfa1def00dac9e, 
			 * hostId=cf7639f34c1f4884ca12b03d46fe17deb90a3dc585e82cc37fc3c9a6, 
			 * addresses=NovaAddresses{addresses={内部网络=[NovaAddress{address=10.50.24.44, type=fixed, version=4, macaddr=fa:16:3e:f3:42:82, }], 
			 * 基础网络=[NovaAddress{address=172.30.249.42, type=fixed, version=4, macaddr=fa:16:3e:08:18:5c,}]}, }, 
			 * hypervisor host=storage3, powerstate=4, instanceName=instance-00000352, vmState=stopped, metadata={}}
			 */
			
			System.out.println("xxxxxxxxxx");
			// list server by id
			Server server = os.compute().servers().get("5a57b5dd-4616-4a1a-a803-4c84469c6898");
			System.out.println(server);
			System.out.println("getVmState =" + server.getVmState());
			System.out.println("getStatus =" + server.getStatus());
			System.out.println("getAccessIPv4 =" + server.getAccessIPv4());
			System.out.println("getId =" + server.getId());   //getAddresses =10.50.24.44
			System.out.println("getAddresses =" + server.getAddresses().getAddresses().get("内部网络").get(0).getAddr());
			/**
			 * getAddresses{内部网络=[NovaAddress{address=10.50.24.44, type=fixed, version=4, macaddr=fa:16:3e:f3:42:82,}],
			 *  基础网络=[NovaAddress{address=172.30.249.42, type=fixed, version=4, macaddr=fa:16:3e:08:18:5c,}]}
			 */
			
			
			
			
		}


}
